package com.wty.mianshi.tree;


/**
 * 树的创建类
 */
public class TreeCreator {
    /**
     * 手动创建一颗树
     * @return
     */
    public TreeNode createSampleTree() {
        TreeNode root = new TreeNode('A');
        root.setLeft(new TreeNode('B'));
        root.getLeft().setLeft(new TreeNode('D'));
        root.getLeft().setRight(new TreeNode('E'));
        root.getLeft().getRight().setLeft(new TreeNode('G'));
        root.setRight(new TreeNode('C'));
        root.getRight().setRight(new TreeNode('F'));
        return root;
    }

    public TreeNode createTree(String preStr,String inStr){
        if(preStr.isEmpty()||inStr==null){
            return null;
        }


        char rootValue=preStr.charAt(0);
        int rootIndex=inStr.indexOf(rootValue);
        TreeNode root=new TreeNode(rootValue);
        root.setLeft(createTree(preStr.substring(1,rootIndex+1),inStr.substring(0,rootIndex)));
        root.setRight(createTree(preStr.substring(rootIndex+1),inStr.substring(rootIndex+1)));
        return root;
    }
}
